package com.me.generatePB;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class AutoGeneratePBUtils {

	/**
	 * 设置名字分割
	 */
	private String spile = "_";

	/**
	 * 生成文件存放路径
	 */
	private String path = "";

	/**
	 * 根据表名字自动生成相应的PBModel对象
	 * 
	 * @param tableName
	 */
	public PBModel getProtocolBufferModel(String tableName) {
		PBModel pbModel = new PBModel();
		DatabaseMetaData dbmd;
		ResultSet tableSet = null;
		try {
			pbModel.setPbFileName(getPBFileName(tableName));
			pbModel.setPbClassName(getPBClassName(tableName));
			dbmd = BaseConnection.con.getMetaData();
			tableSet = dbmd.getColumns(null, null, tableName, "%");
			List<Column> columns = new ArrayList<>();
			while (tableSet.next()) {
				Column column = new Column();
				column.setColumnName(getColumnName(tableSet.getString("COLUMN_NAME")));
				column.setColumnType(getColumnType(tableSet.getString("TYPE_NAME")));
				column.setRemarks(tableSet.getString("REMARKS"));
				columns.add(column);
			}
			pbModel.setColumns(columns);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (tableSet != null) {
					tableSet.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return pbModel;
	}

	/**
	 * 设置Pb文件的名字
	 * 
	 * @param tableName
	 * @return
	 */
	private String getPBClassName(String tableName) {
		// TODO Auto-generated method stub
		String[] strs = tableName.split(spile);
		StringBuffer buffer = new StringBuffer();
		for (String str : strs) {
			buffer.append(str.substring(0, 1).toUpperCase()).append(str.substring(1));
		}
		return buffer.toString();
	}

	/**
	 * 设置Pb的Class名字
	 * 
	 * @param tableName
	 * @return
	 */
	private String getPBFileName(String tableName) {
		// TODO Auto-generated method stub
		String[] strs = tableName.split(spile);
		StringBuffer buffer = new StringBuffer();
		buffer.append("Protoc");
		for (String str : strs) {
			buffer.append(str.substring(0, 1).toUpperCase()).append(str.substring(1));
		}
		return buffer.toString();
	}

	/**
	 * 设置名字
	 * 
	 * @param type
	 * @return
	 */
	private String getColumnType(String type) {
		// TODO Auto-generated method stub
		try {
			type = MySqlData.valueOf(type).pbType;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(type + "-----该数据库类型暂无匹配PB数据类型，请添加后使用！");
		}
		return type;
	}

	/**
	 * 根据类型转换成PB
	 * 
	 * @param name
	 * @return
	 */
	private String getColumnName(String name) {
		// TODO Auto-generated method stub
		String[] strs = name.split(spile);
		StringBuffer buffer = new StringBuffer();
		int i = 1;
		for (String str : strs) {
			if (i == 1) {
				buffer.append(str.substring(0, 1).toLowerCase()).append(str.substring(1));
			} else {
				buffer.append(str.substring(0, 1).toUpperCase()).append(str.substring(1));
			}
			i++;
		}
		return buffer.toString();
	}

	/**
	 * 生成PB文件
	 * 
	 * @return
	 */
	public int generatePB(PBModel pb) {

		BufferedWriter bw = null;
		int index = 1;
		try {
			File pathFile = new File(path);
			if (!pathFile.exists()) {
				pathFile.mkdirs();
			}

			String fileName = path + pb.getPbFileName() + "." + pb.getSuffix();
			File file = new File(fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
			bw = new BufferedWriter(new FileWriter(file));
			bw.write("syntax = \"" + pb.getSyntax() + "\";");
			bw.write("\n\r");
			if (pb.getImportList() != null) {
				for (String str : pb.getImportList()) {
					bw.write("import \"" + str + "\";");
					bw.write("\n\r");
				}
			}
			bw.write("message " + pb.getPbClassName() + "{");
			bw.write("\n");
			if (pb.getColumns() != null) {
				for (Column col : pb.getColumns()) {
					bw.write("    //" + col.getRemarks());
					bw.write("\n");
					bw.write("    " + col.getColumnType() + " " + col.getColumnName() + " = " + index + ";");
					bw.write("\n");
					bw.write("\n");
					index++;
				}
			}
			if (pb.getAdditionalColumns() != null) {
				for (Column col : pb.getAdditionalColumns()) {
					bw.write("    //" + col.getRemarks());
					bw.write("\n");
					bw.write("    " + col.getColumnType() + " " + col.getColumnName() + " = " + index + ";");
					bw.write("\n");
					bw.write("\n");
					index++;
				}
			}
			bw.write("}");
			bw.flush();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (bw != null) {
				try {
					bw.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return 1;
	}

	public String getSpile() {
		return spile;
	}

	public void setSpile(String spile) {
		this.spile = spile;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public static void mian(String args[]) {

	}

}
